package com.huatai.paas.controller;

import com.huatai.common.api.R;
import com.huatai.common.config.MinioAPI;
import com.huatai.common.constant.MinioCommonBucket;
import com.huatai.common.error.exception.ServiceException;
import com.huatai.common.util.DateTimeUtil;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDate;

/**
 * <b>FileUploadController</b>
 *
 * @description: FileUploadController <br>
 * @date: 2024/10/10 15:54 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@RestController
@Api(tags = "文件上传")
public class FileUploadController {
	private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);

	@Autowired
	private MinioAPI minioAPI;

	private final static String SLASH = "/";

	private final static String FILE_NAME_PREFIX_SEPARATOR = "-";

	@Value("${minio.PREURL}")
	private String minioUrl;

	public R uploadFileByType(@RequestParam("file") MultipartFile file ,@RequestParam() String type){
		try (InputStream is = file.getInputStream()) {
			String bucketName = MinioCommonBucket.HUATAI_PUB_BUCKET;
			String objectKey = getObjectKey(file.getSize(), file.getOriginalFilename());
			minioAPI.uploadInputStream(bucketName, objectKey, is, file.getContentType());
			logger.info("上传地址为:{}"+objectKey);
			return R.data(minioUrl+"/"+MinioCommonBucket.HUATAI_PUB_BUCKET+"/"+objectKey);
		} catch (Exception e) {
			logger.error("上传失败，", e);
			throw new ServiceException("上传失败，请重新上传");
		}
	}

	private String getObjectKey(Long fileSize,String fileName) {
		String date = DateTimeUtil.format(LocalDate.now(),"yyyyMMdd");

		StringBuilder objectKey = new StringBuilder(date);
		objectKey.append(SLASH).append(fileSize).append(FILE_NAME_PREFIX_SEPARATOR).append(fileName);
		return objectKey.toString();
	}
}
